package spider

import (
	"crypto/rand"

	"math/big"

	"encoding/json"
	"io/ioutil"
	"priceApi/models"
	"priceApi/utils"
	"strconv"

	"github.com/astaxie/beego/orm"
)

func GetBinanceKline() {
	var symbols = utils.GetSymbolsByConf()

	for _, val := range symbols {
		var jsondata [][]interface{}
		startTime := models.GetKlineLastTime(val)

		url := "https://api.binance.com/api/v1/klines?symbol=" + val + "USDT&interval=1m&startTime=" + strconv.Itoa(int(startTime))
		resp, err := utils.GetBySS(url)
		if err != nil {
			return
		}
		defer resp.Body.Close()
		input, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return
		}
		json.Unmarshal([]byte(input), &jsondata)
		for _, v := range jsondata {
			SaveBinanceKline(val, v)
		}
		//		v0 := jsondata[0]
		//		SaveBinanceKline(val, v0)

		//		for _, v := range jsondata[1:] {
		//			Timer := (int64(v[0].(float64)) - int64(v0[0].(float64))) / 60000

		//			if Timer == 1 {
		//				SaveBinanceKline(val, v)
		//			} else {
		//				i := 1
		//				fmt.Println(Timer)
		//				for int64(i) <= Timer {
		//					if int64(i) == Timer {
		//						SaveBinanceKline(val, v)
		//					} else {
		//						SaveBinanceKlineNewOpenTIme(val, jsondata[MyRand(int64(len(jsondata)))], int64(v0[0].(float64))+int64(i)*60000)
		//					}
		//					i++
		//				}
		//			}
		//			v0 = v
		//		}

	}

}

//备用保存函数
func SaveBinanceKlineNewOpenTIme(symbol string, v []interface{}, opentime int64) {

	o := orm.NewOrm()
	kline := new(models.Kline)
	kline.Symbol = symbol
	kline.Open_time = opentime
	kline.Open = StrToFloat(v[1].(string))
	kline.High = StrToFloat(v[2].(string))
	kline.Low = StrToFloat(v[3].(string))
	kline.Close = StrToFloat(v[4].(string))
	kline.Volume = StrToFloat(v[5].(string))
	kline.Close_time = opentime + 59999
	kline.Quote_asset_volume = StrToFloat(v[7].(string))
	kline.Trades = int64(v[8].(float64))
	kline.Taker_buy_base_asset_volume = StrToFloat(v[9].(string))
	kline.Taker_buy_quote_asset_volume = StrToFloat(v[10].(string))
	kline.Ignore_ = StrToFloat(v[11].(string))

	o.Insert(kline)

}

func SaveBinanceKline(symbol string, v []interface{}) {

	o := orm.NewOrm()
	kline := new(models.Kline)
	kline.Symbol = symbol
	kline.Open_time = int64(v[0].(float64))
	kline.Open = StrToFloat(v[1].(string))
	kline.High = StrToFloat(v[2].(string))
	kline.Low = StrToFloat(v[3].(string))
	kline.Close = StrToFloat(v[4].(string))
	kline.Volume = StrToFloat(v[5].(string))
	kline.Close_time = int64(v[6].(float64))
	kline.Quote_asset_volume = StrToFloat(v[7].(string))
	kline.Trades = int64(v[8].(float64))
	kline.Taker_buy_base_asset_volume = StrToFloat(v[9].(string))
	kline.Taker_buy_quote_asset_volume = StrToFloat(v[10].(string))
	kline.Ignore_ = StrToFloat(v[11].(string))

	o.Insert(kline)

}

//取随机数
func MyRand(maxint int64) int64 {
	max := big.NewInt(maxint)
	i, _ := rand.Int(rand.Reader, max)
	return i.Int64()
}
func StrToFloat(str string) float64 {
	var num, _ = strconv.ParseFloat(str, 64)
	return num
}
